package com.easily.factory.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk代理实现接口，所以没有接口的类是不能使用此代理的
 */
public class JDKProxy extends ProxyObject implements InvocationHandler{

    protected JDKProxy(Object targetObject, AopObject aop,boolean isAllMethodProxy) {
        super(targetObject, aop,isAllMethodProxy);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return this.proxyInvoke(method,args,()-> method.invoke(targetObject, args));
    }

    /**
     * 用jdk的Proxy类创建代理，参数为classLoader, 目标对象的接口，以及InvocationHandler的实现类
     */
    public <T> T getProxy(Class<T> z) {
        return z.cast(Proxy.newProxyInstance(
                targetObject.getClass().getClassLoader(),
                targetObject.getClass().getInterfaces(),
                this));
    }
}
